import SystemUtil from 'utils/systemUtil';

export default class {
  static session = window.sessionStorage;
  static local = window.localStorage;
  static isMiniprogram = process.env.isMiniprogram;

  //设置sessionStorage相应数据
  static setSession(key, value) {
    if (value === undefined) {
      return;
    }

    if (this.isMiniprogram) {
      const app = getApp();
      if (app.globalData === undefined) {
        app.globalData = {};
      }
      app.globalData[key] = value;
      return;
    }

    let obj = {
      data: value
    };
    this.session.setItem(key, JSON.stringify(obj));
  }

  static setLocal(key, value) {
    if (value === undefined) {
      return;
    }
    let obj = {
      data: value
    };

    if (this.isMiniprogram) {
      wx.setStorageSync(key, JSON.stringify(obj))
    } else {
      this.local.setItem(key, JSON.stringify(obj));
    }
  }

  //获取相应数据
  static getSession(key) {
    if (this.isMiniprogram) {
      const app = getApp();
      if (app.globalData === undefined) {
        return null;
      }

      let data = app.globalData[key];
      if (SystemUtil.isEmpty(data)) {
        data = null;
      }
      return data;
    }

    let value = this.session.getItem(key);
    if (SystemUtil.isEmpty(value)) {
      return null;
    }
    value = JSON.parse(value);
    return value.data;
  }

  static getLocal(key) {
    let value;
    if (this.isMiniprogram) {
      value = wx.getStorageSync(key);
    } else {
      value = this.local.getItem(key);
    }
    if (SystemUtil.isEmpty(value)) {
      return null;
    }

    value = JSON.parse(value);
    return value.data;
  }

  //清除相应sessionStorage里的值，key不传为清空sessionStorage里所有值
  static removeSession(key) {
    if (this.isMiniprogram){
      const app = getApp();
      if (key === undefined) {
        app.globalData = {};
      } else {
        let data = app.globalData;
        if (data === undefined) {
          app.globalData = {};
        } else if (data[key] !== undefined) {
          delete data[key];
        }
      }
    }

    if (key === undefined) {
      this.session.clear();
    } else {
      this.session.removeItem(key);
    }
  }

  static removeLocal(key) {
    if (key === undefined) {
      if (this.isMiniprogram) {
        wx.clearStorageSync();
      } else {
        this.local.clear();
      }
    } else {
      if (this.isMiniprogram) {
        wx.removeStorageSync(key);
      } else {
        this.local.removeItem(key);
      }
    }
  }
};
